class Cip::Page < ApplicationRecord
  belongs_to :category
  validates_presence_of :category

  has_attached_file :avatar, styles: { large: "500x500>", medium: "300x300>", thumb: "100x100#" }, preserve_files: true
  validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
  attr_accessor :_destroy_avatar
  before_validation do
    avatar.clear if _destroy_avatar == '1'
  end

  FORWARDING_TYPES = { '普通页面': 'normal' ,'空链接': 'blank', '页面链接': 'page', '分类链接': 'category', '外部链接': 'url' }
  validates_inclusion_of :forwarding_type, in: FORWARDING_TYPES.values

  validates_presence_of :title

  serialize :metadata, JSON

  DEFAULT_AUTHOR = "公共服务中心"
  before_create do
    self.position = (category.pages.maximum(:position) || 0) + 1
    self.author = DEFAULT_AUTHOR if self.author.blank?
  end

  def url
    case forwarding_type
    when 'normal'
      Rails.application.routes.url_helpers.cip_page_path(id)
    when 'page'
      Rails.application.routes.url_helpers.cip_page_path(forwarding_page_id)
    when 'category'
      Rails.application.routes.url_helpers.cip_category_path(forwarding_category_id)
    when 'url'
      forwarding_url
    when 'blank'
      '#'
    end
  end
end
